package com.ruoyi.common.core.utils.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * HTTP工具类
 * 
 * @author ruoyi
 */
public class HttpUtils
{
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 发送GET请求
     * 
     * @param urlString 请求URL
     * @param headers 请求头
     * @return 响应内容
     */
    public static String sendGet(String urlString, Map<String, String> headers)
    {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        
        try
        {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求方法
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(30000);
            
            // 设置请求头
            if (headers != null && !headers.isEmpty())
            {
                for (Map.Entry<String, String> entry : headers.entrySet())
                {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            
            // 发送请求
            connection.connect();
            
            int responseCode = connection.getResponseCode();
            
            if (responseCode == HttpURLConnection.HTTP_OK)
            {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;
                
                while ((line = reader.readLine()) != null)
                {
                    response.append(line);
                }
                
                return response.toString();
            }
            else
            {
                log.error("HTTP请求失败，响应码: {}", responseCode);
                return null;
            }
        }
        catch (Exception e)
        {
            log.error("发送GET请求异常", e);
            return null;
        }
        finally
        {
            try
            {
                if (reader != null)
                {
                    reader.close();
                }
                if (connection != null)
                {
                    connection.disconnect();
                }
            }
            catch (Exception e)
            {
                log.error("关闭连接异常", e);
            }
        }
    }
}

